package com.choosefine.springboot.devops;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Rectangle2D;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebViewSample extends Application {
    private Scene scene;
    Browser browser = null;

    @Override
    public void start(Stage stage) {
        // create the scene
        stage.setTitle("Web View");
        browser = new Browser();
        String url = WebViewSample.class.getResource("/") + "static/command/input.html";
        log.info("即将被打开的url是：\n" + url);
        browser.navigate(url);
        //scene = new Scene(browser, browser.getWidth(), browser.getHeight(), Color.web("#666970"));
        scene = new Scene(browser, 1200, 900, Color.web("#666970"));
        stage.setScene(scene);
        stage.show();
    }

    public static void show(String[] args) {
        launch(args);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

class Browser extends Region {

    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();

    public Browser() {
        //apply the styles
        getStyleClass().add("browser");
        webEngine.setOnResized(
                new EventHandler<WebEvent<Rectangle2D>>() {
                    public void handle(WebEvent<Rectangle2D> ev) {
                        Rectangle2D r = ev.getData();
//                        stage.setWidth(r.getWidth());
//                        stage.setHeight(r.getHeight());
                    }
                });
        getChildren().add(browser);

    }

    public void navigate(String url) {
        webEngine.load(url);
    }

    private Node createSpacer() {
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        return spacer;
    }

    @Override
    protected void layoutChildren() {
        double w = getWidth();
        double h = getHeight();
        layoutInArea(browser, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);
    }

    @Override
    protected double computePrefWidth(double width) {
        return 1200;
    }

    @Override
    protected double computePrefHeight(double height) {
        return 900;
    }
}